﻿using System.IO;

namespace SimpleX
{
    public static class ImageHelper
    {
        public static bool IsImage(string fileFullName)
        {
            if (!File.Exists(fileFullName)) return false;

            var stream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read);
            return IsImage(stream);
        }

        public static bool IsImage(byte[] bytes)
        {
            var stream = new MemoryStream(bytes);
            return IsImage(stream);
        }

        public static bool IsImage(Stream stream)
        {
            try
            {
                var retval = IsJpeg(stream) || IsPng(stream) || IsGif(stream);
                return retval;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                stream?.Close();
                stream?.Dispose();
            }
        }

        public static bool IsJpeg(Stream stream)
        {
            stream.Seek(0, SeekOrigin.Begin);
            var br = new BinaryReader(stream);
            var soi = br.ReadUInt16();
            var marker = br.ReadUInt16();
            return soi == 0xd8ff && (marker & 0xe0ff) == 0xe0ff;
        }

        public static bool IsPng(Stream stream)
        {
            stream.Seek(0, SeekOrigin.Begin);
            var br = new BinaryReader(stream);
            var soi = br.ReadUInt64();
            return soi == 0x0a1a0a0d474e5089;
        }

        public static bool IsGif(Stream stream)
        {
            stream.Seek(0, SeekOrigin.Begin);
            var br = new BinaryReader(stream);
            var soi = br.ReadUInt32();
            var p2 = br.ReadUInt16();
            return soi == 0x38464947 && (p2 == 0x6137 || p2 == 0x6139);
        }
    }
}